#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2025/03/24 16:30
# @Author  : liuyuzhao
# @Site    :
# @File    : login_temu_invoice_driss.py
# @Software: PyCharm
import sys
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

import time
import socket
import json
from pathlib import Path
from filelock import FileLock, Timeout
from tempfile import gettempdir, TemporaryDirectory
from datetime import datetime
from DrissionPage import ChromiumPage
# from pipeline.redis_connect import save_key_redis, query_redis_cookie
from pipeline.sql_connect import WaicangSqlConnect


def find_free_port():
    """找到一个可用的端口，用于浏览器开启远程调试端口，防止端口冲突"""
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(('127.0.0.1', 0))
        return s.getsockname()[1]


# def is_port_available(port=9222, check_scope=100) -> int:
#     """
#     检查端口是否占用，并返回一个未被占用的端口
#     :param port: 默认起始端口
#     :param check_scope: 端口检查范围
#     :return: port
#     """
#     # with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
#     #     for pt in range(port, port + check_scope):
#     #         if s.connect_ex(('127.0.0.1', pt)) != 0:
#     #             return pt
#
#     ports = [54212, 64655, 57881, 53006, 50125, 61859, 58311, 53203, 59204, 49424, 49334, 55919, 55511, 54212, 56618, 51598]
#     # with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
#     #     for pt in ports:
#     #         if s.connect_ex(('127.0.0.1', pt)) != 0:
#     #             return pt
#     return ports[11]

def is_port_available(port=49424, check_scope=100) -> int:
    """
    检查端口是否占用，并返回一个未被占用的端口
    :param port: 默认起始端口
    :param check_scope: 端口检查范围
    :return: port
    """
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        for pt in range(port, port + check_scope):
            lock_dir = Path(gettempdir()) / 'is_port_available'
            lock_dir.mkdir(parents=True, exist_ok=True)
            lock_path = lock_dir / f'port_{pt}.lock'
            # 如果文件不存在，创建文件
            if not lock_path.exists():
                lock_path.touch()

            lock = FileLock(lock_path, timeout=0)
            try:
                with lock:
                    if s.connect_ex(('127.0.0.1', pt)) != 0:
                        return pt
            except Timeout:
                continue


# def check_notice(page):
#     """
#     检查是否有通知类弹框
#     :param page:
#     :return:
#     """
#     notice_div = page.eles("xpath://div[@data-testid='beast-core-modal-body']")
#     if notice_div:
#         time.sleep(3)
#         button = notice_div[0].eles("xpath://button[@data-testid='beast-core-button']")
#         if button:
#             button[0].click()
#             print("弹窗已关闭")


def check_logon_success(page, wc):
    """
    校验登录是否成功
    :param page:
    :return:
    """
    current_url = page.url
    print(current_url)

    login_ele = page.eles("xpath://input[@id='usernameId']")
    if len(login_ele) == 0 and "login" not in current_url:
        print("已经是在登录后的主页页面")
        # check_notice(page=page)

        page.get('https://seller.kuajingmaihuo.com/link-agent-seller?regionList=1,2,3&targetUrl=%2Flabor%2Fsettle')
        time.sleep(5)
        has_x = False
        x_ele = page.ele("xpath://div[@class='delivery-time-modal_close__hK7oO']")
        if x_ele:
            has_x=True
            x_ele.click()
            time.sleep(1)
        # 欧区
        button_ele = page.ele("xpath://span[contains(text(), '欧区')]")
        if button_ele:
            europe_ele = button_ele
            europe_ele.click()
            time.sleep(15)
            cookies = page.cookies
            print(cookies)
            # save_key_redis(name="temu", key="temu_shop", cookie=json.dumps(cookies, ensure_ascii=False))
            update_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            wc.save_temu_seller_cookie(cookies=json.dumps(cookies, ensure_ascii=False), update_time=update_time, platform_name="temu_invoice_europe")
            time.sleep(15)

            # 全球
            page.get('https://seller.kuajingmaihuo.com/link-agent-seller?regionList=1,2,3&targetUrl=%2Flabor%2Fsettle')
            page.wait.load_complete()
            if has_x:
                page.ele("xpath://div[@class='delivery-time-modal_close__hK7oO']").click()
                time.sleep(1)
            globe = page.ele("xpath://div[contains(text(), '全球')]").click()
            time.sleep(15)
            cookies = page.cookies
            print(cookies)
            # save_key_redis(name="temu", key="temu_shop", cookie=json.dumps(cookies, ensure_ascii=False))
            update_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            wc.save_temu_seller_cookie(cookies=json.dumps(cookies, ensure_ascii=False), update_time=update_time, platform_name="temu_invoice_globe")
            time.sleep(15)

            # 美国
            page.get('https://seller.kuajingmaihuo.com/link-agent-seller?regionList=1,2,3&targetUrl=%2Flabor%2Fsettle')
            page.wait.load_complete()
            if has_x:
                page.ele("xpath://div[@class='delivery-time-modal_close__hK7oO']").click()
                time.sleep(1)
            globe = page.ele("xpath://span[normalize-space(text())='美国']").click()
            time.sleep(15)
            cookies = page.cookies
            print(cookies)
            # save_key_redis(name="temu", key="temu_shop", cookie=json.dumps(cookies, ensure_ascii=False))
            update_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            wc.save_temu_seller_cookie(cookies=json.dumps(cookies, ensure_ascii=False), update_time=update_time, platform_name="temu_invoice_american")
        return True

    return False


def login(page, user, pwd, wc):
    """
    执行登录
    :param page:
    :param user:
    :param pwd:
    :param wc:
    :return:
    """
    # 1 输入账号
    page.eles("xpath://input[@id='usernameId']")[0].clear()
    time.sleep(3)
    page.eles("xpath://input[@id='usernameId']")[0].input(user)
    time.sleep(3)
    print("【输入账号：{}】成功".format(user))

    # 2 输入密码
    page.eles("xpath://input[@id='passwordId']")[0].clear()
    time.sleep(3)
    page.eles("xpath://input[@id='passwordId']")[0].input(pwd)
    time.sleep(3)
    print("【输入密码:{}】成功".format(pwd))

    # 3.1 点击同意
    agree_ele = page.eles("xpath://div[@data-testid='beast-core-checkbox-checkIcon']/input")
    print("===agree===", len(agree_ele))
    if agree_ele:
        agree_ele[0].click()
        time.sleep(2)
        print("点击【同意协议】")

    # 3 点击登录
    button_ele = page.eles("xpath://button[@type='button']")
    button_ele[0].click()
    print("【点击登录】成功")
    time.sleep(3)
    url_now = page.url
    print("--111--", url_now)
    time.sleep(3)
    page.ele("xpath://*[@data-testid='beast-core-icon-check']").click()
    # enter_ele = page.eles("xpath://div[contains(text(), '进入')]")
    # print("==enter_ele===", enter_ele)
    # if len(enter_ele):
    # enter_ele[0].click()
    # print("进入卖家中心")
    #
    # check_notice(page=page)
    #
    # shop_div = page.eles("xpath://div[@class='layout_mallInfo__ddeaA']")
    # if shop_div:
    #     print("当前店铺：", shop_div[0].text)
    page.get('https://seller.kuajingmaihuo.com/link-agent-seller?regionList=1,2,3&targetUrl=%2Flabor%2Fsettle')
    time.sleep(5)
    has_x = False
    x_ele = page.ele("xpath://div[@class='delivery-time-modal_close__hK7oO']")
    if x_ele:
        has_x = True
        x_ele.click()
        time.sleep(1)

    # 欧区
    button_ele = page.ele("xpath://span[contains(text(), '欧区')]")
    if button_ele:
        europe_ele = button_ele
        europe_ele.click()
        time.sleep(15)
        cookies = page.cookies
        print(cookies)
        # save_key_redis(name="temu", key="temu_shop", cookie=json.dumps(cookies, ensure_ascii=False))
        update_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        wc.save_temu_seller_cookie(cookies=json.dumps(cookies, ensure_ascii=False), update_time=update_time, platform_name="temu_invoice_europe")
        time.sleep(15)

        # 欧区
        page.get('https://seller.kuajingmaihuo.com/link-agent-seller?regionList=1,2,3&targetUrl=%2Flabor%2Fsettle')
        page.wait.load_complete()
        if has_x:
            page.ele("xpath://div[@class='delivery-time-modal_close__hK7oO']").click()
            time.sleep(1)
        globe = page.ele("xpath://div[contains(text(), '欧区')]").click()
        time.sleep(15)
        cookies = page.cookies
        print(cookies)
        # save_key_redis(name="temu", key="temu_shop", cookie=json.dumps(cookies, ensure_ascii=False))
        update_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        wc.save_temu_seller_cookie(cookies=json.dumps(cookies, ensure_ascii=False), update_time=update_time, platform_name="temu_invoice_globe")
        time.sleep(15)

        # 美国
        page.get('https://seller.kuajingmaihuo.com/link-agent-seller?regionList=1,2,3&targetUrl=%2Flabor%2Fsettle')
        page.wait.load_complete()
        if has_x:
            page.ele("xpath://div[@class='delivery-time-modal_close__hK7oO']").click()
            time.sleep(1)
        globe = page.ele("xpath://span[normalize-space(text())='美国']").click()
        time.sleep(15)
        cookies = page.cookies
        print(cookies)
        # save_key_redis(name="temu", key="temu_shop", cookie=json.dumps(cookies, ensure_ascii=False))
        update_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        wc.save_temu_seller_cookie(cookies=json.dumps(cookies, ensure_ascii=False), update_time=update_time, platform_name="temu_invoice_american")

        if page.tabs:
            page.close_other_tabs()
            page.close_tabs()
        wc.close()
        return cookies


def login_temu_driss():
    """
    登录temu  4594954014482 是主店，   634418209736233 是子店
    """
    # page = ChromiumPage()
    wc = WaicangSqlConnect()
    # free_port = is_port_available()
    # addr_driver_opts = "127.0.0.1:{}".format(free_port)
    # print(addr_driver_opts)
    # page = ChromiumPage(addr_driver_opts=addr_driver_opts)
    page = ChromiumPage()

    cookies = {}
    success_png_path = "./login_temu_driss.png"
    failed_png_path = "./login_temu_failed.png"
    if os.path.exists(success_png_path):
        os.remove(success_png_path)

    if os.path.exists(failed_png_path):
        os.remove(failed_png_path)

    try:
        # login_url = "https://kuajing.pinduoduo.com/login?redirectUrl=https%3A%2F%2Fkuajing.pinduoduo.com%2Fmain%2Fsale-manage%2Fmain"
        login_url = "https://seller.kuajingmaihuo.com"
        # user = "18125085548"
        # pwd = "Minisous2023!"

        # 这个比较少登录
        # user = "13711506283"
        # pwd = "Miniso2023!"

        # # 20241220更新为以下帐号   验证码找  霍建敏  主账号不建议使用
        # user = "19927584332"
        # pwd = "Minisohotsale2023!"

        # 20241220更新为以下帐号   验证码找  郭占豪  子账号
        user = "13728030375"
        pwd = "Miniso2024"


        page.get(login_url)
        time.sleep(1)
        current_url = page.url
        print(current_url)
        # old_cookies =query_redis_cookie(name="temu", key="temu_shop")
        old_cookies = wc.query_temu_seller_cookie(platform_name="temu_seller")
        if old_cookies:
            ck = json.loads(old_cookies)
            print(ck)
            page.set.cookies(ck)
            print("cookie更新")
            page.get(login_url)
            time.sleep(1)
            if check_logon_success(page=page, wc=wc):
                print("登录成功")
                cookies = page.cookies
                if page.tabs:
                    page.close_other_tabs()
                    page.close_tabs()
                wc.close()
                return cookies

            return login(page=page, user=user, pwd=pwd, wc=wc)

        else:
            if check_logon_success(page=page, wc=wc):
                cookies = page.cookies
                if page.tabs:
                    page.close_other_tabs()
                    page.close_tabs()
                wc.close()
                return cookies

            return login(page=page, user=user, pwd=pwd, wc=wc)

    except Exception as e:
        page.get_screenshot(failed_png_path)
        import traceback
        print(traceback.format_exc())
        print("执行登录异常")
        page.close_other_tabs()
        page.close_tabs()
        print("程序运行结束")
        return False


if __name__ == '__main__':
    # wc = WaicangSqlConnect()
    # cookies = {
    #     'api_uid': 'CmZlhWdkyVasKwBPuW6vAg==',
    #     '_nano_fp': 'Xpmqn0Eyl0XbX0XynT_0_sDoWAC~tLECm7Z01d6w',
    #     '_bee': 'q2dVgho1usZpkZoCSWDRwb3Zi8TXDamn',
    #     '_f77': '699f694c-0dd7-4f9e-a0da-17b3d0156685',
    #     '_a42': 'd8fba583-44b3-4b78-ad42-846ef250aee7',
    #     'rckk': 'q2dVgho1usZpkZoCSWDRwb3Zi8TXDamn',
    #     'ru1k': '699f694c-0dd7-4f9e-a0da-17b3d0156685',
    #     'ru2k': 'd8fba583-44b3-4b78-ad42-846ef250aee7',
    #     'SUB_PASS_ID': 'eyJ0IjoiSDZWZnQ3UElQTGQwb0JvMWFhYUExUk9nWWJaR3RhNEhkUlE3SGlzTXZzejZNdDI3RjIwOFp6Vk9BblVsR2lYcyIsInYiOjEsInMiOjEwMDAwLCJ1IjoyMjg5OTA1ODMxNjA0Nn0=',
    # }
    # update_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    # wc.save_temu_seller_cookie(cookies=json.dumps(cookies, ensure_ascii=False), update_time=update_time,
    #                            platform_name="temu_seller")

    login_temu_driss()
